package com.ibm.risk.irmp.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
public class HDFSUtilCmd implements HDFSUtil {
    private static final Logger log = LoggerFactory.getLogger(HDFSUtilCmd.class);
    @Value("${app.rwa.bin.hdfs.get:./bin/hdfs-get.sh}")
    private String hdfsGetCmd;
    @Value("${app.rwa.bin.hdfs.put:./bin/hdfs-put.sh}")
    private String hdfsPutCmd;
    @Value("${app.rwa.bin.hdfs.list:./bin/hdfs-ls.sh}")
    private String hdfsListCmd;

    /**
     * 上传本地文件到HDFS
     *
     * @param localFile
     * @param hdfsFileName e.g. hdfs://192.168.1.103:9000/xxx
     */
    public void upload(File localFile, String hdfsFileName) throws Exception {
        log.info("upload from {} to hdfs at {}", localFile, hdfsFileName);
        CmdExecutionUtils.executCmd(hdfsPutCmd, 100, localFile.toString(), hdfsFileName);
    }

    /**
     * HDFS文件下载
     *
     * @param hdfsFileName  HDFS文件路径
     * @param localFileName 本地文件路径
     */
    public void download(String hdfsFileName, String localFileName) throws Exception {
        log.info("down from hdfs {} to local at {}", hdfsFileName, localFileName);
        CmdExecutionUtils.executCmd(hdfsGetCmd, 100, hdfsFileName, localFileName);
    }

    @Override
    public String[] list(String path) throws Exception {
        log.info("list from hdfs {}", path);
        String s = CmdExecutionUtils.executCmd(hdfsListCmd, 100, path);
        return s.split("\\r\\n");
    }

}
